package net.ifilm.aspect;

import net.ifilm.common.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

/**
 *
 * Controller方法拦截
 *
 * CreateBy: <a href="wangjunneil@gmail.com">Calvin</a>
 * CreateTime: 2013-07-07 17:09
 */
public class LogInterceptor extends HandlerInterceptorAdapter {

    /**
     * 日志对象
     */
    private static Log log = LogFactory.getLog(LogInterceptor.class);

    /**
     * 线程本地化存储对象
     */
    private static final ThreadLocal<StopWatch> stopWatchThreadLocal = new ThreadLocal<StopWatch>();

    /**
     * 请求跳转的页面
     */
    private String viewName;

    // ------------------------------------------------------------------------------------------------

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("---------------------------------------------------------------------------------------");
            log.debug("request url " + request.getRequestURI() + " begin parameters: " + parameterList(request));
        }

        if (Constants.performance) {
            StopWatch stopWatch = new StopWatch(handler.toString());
            stopWatch.start(request.getRequestURI());
            stopWatchThreadLocal.set(stopWatch);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) { // 针对ajax提交的请求时modelAndView可能为空
            viewName = modelAndView.getViewName();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (Constants.performance) {
            StopWatch stopWatch = stopWatchThreadLocal.get();
            if (stopWatch != null && stopWatch.isRunning()) {
                stopWatch.stop();
                log.info(stopWatch.prettyPrint());
                stopWatchThreadLocal.set(null);
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("response url " + request.getRequestURI() + " finished and forward " + viewName);
        }
    }

    private String parameterList(HttpServletRequest request) {
        StringBuffer parameters = new StringBuffer();

        Enumeration<String> enumeration = request.getParameterNames();
        String paranName = null;
        String paramValue = null;
        parameters.append('[').append(' ');
        while (enumeration.hasMoreElements()) {
            paranName = enumeration.nextElement();
            paramValue = request.getParameter(paranName);
            parameters.append(paranName).append('=').append(paramValue).append(' ');
        }
        parameters.append(']');

        return parameters.toString();
    }

} ///:~
